How Do I Use Offset Method In JQuery With Examples

admin_img Posted By Bajarangi soft , Posted On 16-10-2020

In JQuery The offset() method which is used to set or returns the offset coordinates of the selected element.So today In this article we discuss how to use it

How Do I Use Offset Method In JQuery With Examples

Syntax:
 

$(selector).offset()

Parameters: Parameter does not required.
 

$(selector).offset({top:value, left:value})

Parameters: The parameter is required when set the offset.
 

$(selector).offset( function(index, offset) )

Parameters: This method set the offset using function. The parameter used in this method is optional. The index parameter is used to return the position of set element and offset return the coordinate of selected element.

Return Value: This method returns the co-ordinate of matched elements.

Example(1)

Step 1:Create index.html file and implement below code.

 

<div class="div1">
    <!-- Click on paragraph -->
    <h2>Welcome to Bajarangisoft</h2>
    <button class="btn btn-success">Click Here!</button>
</div>



Step 2:Implement jQuery to use offset() method.
 

<script>
    $(document).ready(function() {
        $("button").click(function() {
            $("h2").offset({top: 100, left: 140});
        });
    });
</script>


Complete Code For Using offset Method In JQuery
 

<!DOCTYPE html>
<html>
<head>
    <title>How Do I Use Offset Method In JQuery With Examples</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<style>
    body {
        background: grey;
    }

</style>

<body>
<div class="container">
    <br><br><br>
    <div class="text-center">
        <h1 id="color" style="color: White;">Use Offset Method In JQuery </h1>
    </div>
    <br>
    <div class="col-md-2"></div>
    <div class="col-md-8">
        <div class="well">

            <div class="div1">
                <!-- Click on paragraph -->
                <h2>Welcome to Bajarangisoft</h2>
                <button class="btn btn-success">Click Here!</button>
            </div>
            <script>
                $(document).ready(function() {
                    $("button").click(function() {
                        $("h2").offset({top: 100, left: 140});
                    });
                });
            </script>
        </div>
    </div>
    <div class="col-md-2"></div>
</div>
</body>
</html>

Related Post